// import io from 'socket.io-client';
import Cookies from 'js-cookie';
let util = {

};
util.title = function (title) {
    title = title || '综合权限管理系统-基础模版';
    window.document.title = title;
};

util.inOf = function (arr, targetArr) {
    let res = true;
    arr.map(item => {
        if (targetArr.indexOf(item) < 0) {
            res = false;
        }
    });
    return res;
};

util.oneOf = function (ele, targetArr) {
    if (targetArr.indexOf(ele) >= 0) {
        return true;
    } else {
        return false;
    }
};

//验证权限是否显示
util.showThisRoute = function (name, hasPermissions) {
    let isAuth = false;
    for(let perm of hasPermissions) {
      if(name + ':view' === perm) {
        isAuth = true;
        break;
      }
    }
    return isAuth;
};

util.getRouterObjByName = function (routers, name) {
    let routerObj = {};
    routers.forEach(item => {
        if (item.name === 'otherRouter') {
            item.children.forEach((child, i) => {
                if (child.name === name) {
                    routerObj = item.children[i];
                }
            });
        } else {
            if (item.children.length === 1) {
                if (item.children[0].name === name) {
                    routerObj = item.children[0];
                }
            } else {
                item.children.forEach((child, i) => {
                    if (child.name === name) {
                        routerObj = item.children[i];
                    }
                });
            }
        }
    });
    return routerObj;
};

util.handleTitle = function (vm, item) {
    if (typeof item.title === 'object') {
        return vm.$t(item.title.i18n);
    } else {
        return item.title;
    }
};

util.setCurrentPath = function (vm, name) {
    let title = '';
    let isOtherRouter = false;
    vm.$store.state.app.routers.forEach(item => {
        if (item.children.length === 1) {
            if (item.children[0].name === name) {
                title = util.handleTitle(vm, item);
                if (item.name === 'otherRouter') {
                    isOtherRouter = true;
                }
            }
        } else {
            item.children.forEach(child => {
                if (child.name === name) {
                    title = util.handleTitle(vm, child);
                    if (item.name === 'otherRouter') {
                        isOtherRouter = true;
                    }
                }
            });
        }
    });
    let currentPathArr = [];
    if (name === 'home_index') {
        currentPathArr = [
            {
                title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.app.routers, 'home_index')),
                path: '',
                name: 'home_index'
            }
        ];
    } else if ((name.indexOf('_index') >= 0 || isOtherRouter) && name !== 'home_index') {
        currentPathArr = [
            {
                title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.app.routers, 'home_index')),
                path: '/home',
                name: 'home_index'
            },
            {
                title: title,
                path: '',
                name: name
            }
        ];
    } else {
        let currentPathObj = vm.$store.state.app.routers.filter(item => {
            if (item.children.length <= 1) {
                return item.children[0].name === name;
            } else {
                let i = 0;
                let childArr = item.children;
                let len = childArr.length;
                while (i < len) {
                    if (childArr[i].name === name) {
                        return true;
                    }
                    i++;
                }
                return false;
            }
        })[0];
        if(currentPathObj) {
          if (currentPathObj.children.length <= 1 && currentPathObj.name === 'home') {
              currentPathArr = [
                  {
                      title: '首页',
                      path: '',
                      name: 'home_index'
                  }
              ];
          } else if (currentPathObj.children.length <= 1 && currentPathObj.name !== 'home') {
              currentPathArr = [
                  {
                      title: '首页',
                      path: '/home',
                      name: 'home_index'
                  },
                  {
                      title: currentPathObj.title,
                      path: '',
                      name: name
                  }
              ];
          } else {
              let childObj = currentPathObj.children.filter((child) => {
                  return child.name === name;
              })[0];
              currentPathArr = [
                  {
                      title: '首页',
                      path: '/home',
                      name: 'home_index'
                  },
                  {
                      title: currentPathObj.title,
                      path: '',
                      name: currentPathObj.name
                  },
                  {
                      title: childObj.title,
                      path: currentPathObj.path + '/' + childObj.path,
                      name: name
                  }
              ];
          }
        }
    }
    vm.$store.commit('setCurrentPath', currentPathArr);

    return currentPathArr;
};

//点击菜单打开新的标签
util.openNewPage = function (vm, name, argu, query) {
    //获取打开的标签页
    let pageOpenedList = vm.$store.state.app.pageOpenedList;
    let openedPageLen = pageOpenedList.length;
    let i = 0;
    //初始化未打开
    let tagHasOpened = false;
    //遍历所有的标签
    while (i < openedPageLen) {
        //如果相等，说明点击左侧菜单时的页面已经出现在标签里
        if (name === pageOpenedList[i].name) {  // 页面已经打开
            vm.$store.commit('pageOpenedList', {
                index: i,
                argu: argu,
                query: query
            });
            tagHasOpened = true;
            break;
        }
        i++;
    }
    //如果没有出现在标签里，则重新打开标签
    if (!tagHasOpened) {
        let tag = vm.$store.state.app.tagsList.filter((item) => {
            if (item.children) {
                return name === item.children[0].name;
            } else {
                return name === item.name;
            }
        });
        tag = tag[0];
        if(tag) {
          tag = tag.children ? tag.children[0] : tag;
          if (argu) {
              tag.argu = argu;
          }
          if (query) {
              tag.query = query;
          }
          vm.$store.commit('increateTag', tag);
        }
    }
    vm.$store.commit('setCurrentPageName', name);
};

util.toDefaultPage = function (routers, name, route, next) {
    let len = routers.length;
    let i = 0;
    let notHandle = true;
    while (i < len) {
        if (routers[i].name === name && routers[i].redirect === undefined) {
            route.replace({
                name: routers[i].children[0].name
            });
            notHandle = false;
            next();
            break;
        }
        i++;
    }
    if (notHandle) {
        next();
    }
};

//建立连接
// util.createSocket = function(userId) {
  //建立socket.io连接
  // const msgSocket = io('http://localhost:4001');
  // window.msgSocket = msgSocket;
  //建立socket.io连接
  //假设node服务器部署后的地址为：https://www.example.com/ws
  //则：ws_host='https://www.example.com'
  //const msgSocket = io(`${WS_HOST}`, {
  //  secure: true,
  // path: '/ws/socket.id'
  //})
  // msgSocket.on('connect', () => {
  //   msgSocket.emit('user_login', {
  //     userId: userId,
  //     tokenId: Cookies.get('loozb_token'),
  //     socketId: msgSocket.id
  //   })
  // });
  //接收数据推送
  // msgSocket.on('receive_message', function (response) {
  //   if(response) {
  //     const {data} = response;
  //     if(data) {
  //       commit('receiveMessage', data);
  //     }
  //   }
  // });
// }

export default util;
